import { Button, message, RangePicker, Space } from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { omit } from 'xe-utils'

import { cinemaApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

import {
  couponTypeOptions,
  movieOrderStatusMap,
  movieOrderStatusOptions,
  movieOrderThirdStatusMap,
  refundStatusOptions
} from '../../order/constants'

export default defineComponent({
  name: 'DyOrderManage',
  setup() {
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)
    const times = ref([] as any[])
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        formConfig: {
          items: [
            {
              title: '影院名称',
              field: 'cinemaName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入影院名称',
                  allowClear: true
                }
              }
            },
            {
              title: '电影名称',
              field: 'movieName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入电影名称',
                  allowClear: true
                }
              }
            },
            {
              title: '订单编号',
              field: 'orderNo',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入订单编号',
                  allowClear: true
                }
              }
            },
            {
              title: '订单状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '请选择',
                  allowClear: true
                },
                options: movieOrderStatusOptions
              }
            },
            {
              title: '手机号',
              field: 'phone',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入手机号',
                  allowClear: true
                }
              }
            },
            {
              title: '支付时间',
              field: 'startTime',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['payStartTime', 'payEndTime']
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '订单编号',
            field: 'orderNo',
            minWidth: 220
          },
          {
            title: '第三方订单号',
            field: 'tradeNo',
            minWidth: 220
          },
          {
            title: '影院名称',
            field: 'cinemaName',
            minWidth: 200
          },
          {
            title: '电影名称',
            field: 'movieName',
            minWidth: 200
          },
          {
            title: '状态',
            field: 'status',
            minWidth: 120,
            formatter: ({ cellValue }) => {
              return movieOrderStatusMap[cellValue]
            }
          },
          {
            title: '退款方式',
            field: 'refundType',

            formatter: ({ cellValue }) => {
              return optionsToMap(refundStatusOptions)[cellValue]
            }
          },
          {
            title: '第三方状态',
            field: 'thirdStatus',

            formatter: ({ cellValue }) => {
              return movieOrderThirdStatusMap[cellValue]
            }
          },
          {
            title: '第三方售价',
            field: 'thirdPrice',
            minWidth: 150,
            formatter: ({ cellValue }) => {
              return `￥${cellValue}`
            }
          },
          {
            title: '我方售价',
            minWidth: 150,
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '数量',
            field: 'num'
          },
          {
            title: '优惠券',

            slots: {
              default: 'couponInfo'
            }
          },
          {
            title: '实付金额',
            minWidth: 150,
            slots: {
              default: 'payPrice'
            }
          },
          {
            title: '下单人',
            field: 'member'
          },
          {
            title: '下单人手机号',
            field: 'phone',
            minWidth: 120
          },
          {
            title: '下单时间',
            field: 'orderTime',
            minWidth: 170,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '支付时间',
            field: 'payTime',
            minWidth: 170,
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '发起售后时间',
            field: 'refundTime',
            formatter: TABLE_FORMAT.Date,
            minWidth: 170
          },
          {
            title: '退款微信流水号',
            field: 'wxRefundId',
            minWidth: 170
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 150
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              form = omit(form, ['startTime', 'endTime'])
              const data = await cinemaApi.getOrderList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()

    function handleAfterSale(row) {
      showConfirm({
        content: '是否确认售后，发起后将原路退款给到用户并生成新的售后订单？',
        onOk: async () => {
          try {
            await cinemaApi.orderRefund(row.orderNo)
            await tableRef.value.table.commitProxy('query')
            message.success('操作完成')
          } catch (error) {}
        }
      })
    }

    function handleOrderDetail(row) {
      router.push({
        name: 'DyOrderDetailManage',
        query: { orderNo: row.orderNo }
      })
    }

    function handleButtonShow(row) {
      if (row.payTime) {
        return row.status == 1 || row.status == 2
      } else {
        return false
      }
    }

    return {
      tableRef,
      tableConfig,
      times,
      handleAfterSale,
      handleOrderDetail,
      handleButtonShow
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            timeSelect: () => {
              return (
                <Space>
                  <RangePicker v-model:value={this.times} />
                </Space>
              )
            },
            couponInfo: ({ row }) => {
              if (row.couponType) {
                return (
                  <Space>
                    {`${optionsToMap(couponTypeOptions)[row.couponType]} ${
                      row.discount
                    }折`}
                  </Space>
                )
              }
              return '无'
            },
            salePrice: ({ row }) => {
              return <Space>{handlePrice(row.price, row.gold)}</Space>
            },
            payPrice: ({ row }) => {
              return <Space>{handlePrice(row.realPrice, row.realGold)}</Space>
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleOrderDetail(row)}
                >
                  订单详情
                </Button>
                <Button
                  type="link"
                  size="small"
                  disabled={!this.handleButtonShow(row)}
                  onClick={() => this.handleAfterSale(row)}
                >
                  售后
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
